// API 测试工具渲染器 - 专业级增强版
window.APITesterRenderer = class APITesterRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="send" class="w-8 h-8 inline mr-3 text-green-600"></i>
                API 测试工具
                <span class="text-lg text-gray-500 font-normal">专业级功能</span>
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">强大的API测试工具，支持环境变量、测试脚本、批量运行、代码生成等专业级功能。</p>
            </div>

            <!-- 顶部工具栏 -->
            <div class="bg-white rounded-xl shadow-sm border mb-6">
                <div class="p-4 border-b">
                    <div class="flex items-center justify-between flex-wrap gap-4">
                        <!-- 环境选择器 -->
                        <div class="flex items-center gap-2">
                            <label class="text-sm font-medium text-gray-700">环境:</label>
                            <select id="environment-select" class="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500 text-sm">
                                <option value="default">默认环境</option>
                            </select>
                            <button id="manage-environments" class="text-blue-600 hover:text-blue-700 text-sm flex items-center">
                                <i data-feather="settings" class="w-4 h-4 mr-1"></i>
                                管理
                            </button>
                        </div>
                        
                        <!-- 全局功能 -->
                        <div class="flex items-center gap-2">
                            <button id="run-collection" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                                <i data-feather="play" class="w-4 h-4 mr-2"></i>
                                批量运行
                            </button>
                            <button id="code-generator" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                                <i data-feather="code" class="w-4 h-4 mr-2"></i>
                                生成代码
                            </button>
                            <button id="performance-analyzer" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                                <i data-feather="activity" class="w-4 h-4 mr-2"></i>
                                性能分析
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 请求配置区域 -->
            <div class="bg-white rounded-xl shadow-sm border mb-6">
                <div class="p-6">
                    <!-- URL和方法 -->
                    <div class="flex gap-3 mb-6">
                        <select 
                            id="http-method" 
                            class="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-medium"
                        >
                            <option value="GET">GET</option>
                            <option value="POST">POST</option>
                            <option value="PUT">PUT</option>
                            <option value="PATCH">PATCH</option>
                            <option value="DELETE">DELETE</option>
                            <option value="HEAD">HEAD</option>
                            <option value="OPTIONS">OPTIONS</option>
                        </select>
                        <input 
                            type="text" 
                            id="request-url" 
                            class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500" 
                            placeholder="输入API地址，支持变量如: {{baseUrl}}/users/{{userId}}"
                            value="https://jsonplaceholder.typicode.com/posts/1"
                        >
                        <button 
                            id="send-request" 
                            class="bg-green-600 hover:bg-green-700 text-white font-bold px-8 py-3 rounded-lg transition duration-200 flex items-center"
                        >
                            <i data-feather="send" class="w-4 h-4 mr-2"></i>
                            发送
                        </button>
                    </div>

                    <!-- 工具栏 -->
                    <div class="flex flex-wrap gap-3 mb-6">
                        <button 
                            id="import-curl" 
                            class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center text-sm"
                        >
                            <i data-feather="code" class="w-4 h-4 mr-2"></i>
                            导入cURL
                        </button>
                        <button 
                            id="export-curl" 
                            class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center text-sm"
                        >
                            <i data-feather="terminal" class="w-4 h-4 mr-2"></i>
                            导出cURL
                        </button>
                        <button 
                            id="save-request" 
                            class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center text-sm"
                        >
                            <i data-feather="bookmark" class="w-4 h-4 mr-2"></i>
                            保存请求
                        </button>
                        <select 
                            id="template-select" 
                            class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 text-sm"
                        >
                            <option value="">选择模板...</option>
                            <option value="rest-get">REST GET</option>
                            <option value="rest-post">REST POST</option>
                            <option value="form-data">表单数据</option>
                            <option value="auth-bearer">Bearer认证</option>
                            <option value="file-upload">文件上传</option>
                            <option value="graphql">GraphQL</option>
                        </select>
                        <button 
                            id="clear-all" 
                            class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center text-sm"
                        >
                            <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                            清空
                        </button>
                    </div>

                    <!-- 选项卡导航 -->
                    <div class="border-b border-gray-200 mb-6">
                        <nav class="-mb-px flex space-x-8">
                            <button id="tab-headers" class="tab-button py-2 px-1 border-b-2 border-green-500 font-medium text-sm text-green-600">
                                请求头
                            </button>
                            <button id="tab-body" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300">
                                请求体
                            </button>
                            <button id="tab-auth" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300">
                                认证
                            </button>
                            <button id="tab-params" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300">
                                参数
                            </button>
                            <button id="tab-pre-script" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300">
                                <i data-feather="code" class="w-4 h-4 inline mr-1"></i>
                                前置脚本
                            </button>
                            <button id="tab-tests" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300">
                                <i data-feather="check-square" class="w-4 h-4 inline mr-1"></i>
                                测试脚本
                            </button>
                        </nav>
                    </div>

                    <!-- 请求头面板 -->
                    <div id="panel-headers" class="tab-panel">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="font-medium text-gray-700">请求头</h4>
                                <button 
                                    id="add-header" 
                                    class="text-green-600 hover:text-green-700 text-sm flex items-center"
                                >
                                    <i data-feather="plus" class="w-4 h-4 mr-1"></i>
                                    添加
                                </button>
                            </div>
                            <div id="headers-container" class="space-y-2">
                                <div class="flex gap-2 header-row">
                                    <input type="text" placeholder="Header名称" class="flex-1 px-3 py-2 border border-gray-300 rounded header-name-input" value="Content-Type">
                                    <input type="text" placeholder="Header值" class="flex-1 px-3 py-2 border border-gray-300 rounded" value="application/json">
                                    <button class="text-red-500 hover:text-red-700 remove-header">
                                        <i data-feather="x" class="w-4 h-4"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 请求体面板 -->
                    <div id="panel-body" class="tab-panel hidden">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="font-medium text-gray-700">请求体</h4>
                                <div class="flex items-center gap-2">
                                    <select 
                                        id="body-type" 
                                        class="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500"
                                    >
                                        <option value="none">无</option>
                                        <option value="json">JSON</option>
                                        <option value="form">表单数据</option>
                                        <option value="text">纯文本</option>
                                        <option value="xml">XML</option>
                                        <option value="binary">二进制</option>
                                        <option value="graphql">GraphQL</option>
                                    </select>
                                    <!-- JSON工具栏 -->
                                    <div id="json-toolbar" class="flex gap-1 hidden">
                                        <button 
                                            id="format-json" 
                                            class="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                                            title="格式化JSON"
                                        >
                                            格式化
                                        </button>
                                        <button 
                                            id="minify-json" 
                                            class="px-2 py-1 text-xs bg-orange-100 text-orange-700 rounded hover:bg-orange-200 transition-colors"
                                            title="压缩JSON"
                                        >
                                            压缩
                                        </button>
                                        <button 
                                            id="validate-json" 
                                            class="px-2 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
                                            title="验证JSON"
                                        >
                                            验证
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- JSON状态指示器 -->
                            <div id="json-status" class="hidden mb-2 text-sm flex items-center gap-2">
                                <span id="json-status-icon"></span>
                                <span id="json-status-text"></span>
                            </div>
                            
                            <div id="body-content">
                                <div class="relative">
                                    <textarea 
                                        id="body-text" 
                                        class="w-full h-40 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm resize-vertical hidden"
                                        placeholder="输入请求体内容...支持变量如 {{token}}"
                                    ></textarea>
                                    <!-- 字符计数 -->
                                    <div id="body-stats" class="absolute bottom-2 right-2 text-xs text-gray-500 bg-white px-2 py-1 rounded shadow-sm hidden">
                                        <span id="char-count">0</span> 字符 | <span id="line-count">1</span> 行
                                    </div>
                                </div>
                                
                                <div id="form-fields" class="space-y-2 hidden">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-sm font-medium text-gray-700">表单字段</span>
                                        <div class="flex gap-2">
                                            <button 
                                                id="bulk-add-fields" 
                                                class="text-blue-600 hover:text-blue-700 text-sm flex items-center"
                                                title="批量添加字段"
                                            >
                                                <i data-feather="list" class="w-4 h-4 mr-1"></i>
                                                批量添加
                                            </button>
                                            <button 
                                                id="add-form-field" 
                                                class="text-green-600 hover:text-green-700 text-sm flex items-center"
                                            >
                                                <i data-feather="plus" class="w-4 h-4 mr-1"></i>
                                                添加字段
                                            </button>
                                        </div>
                                    </div>
                                    <div id="form-container"></div>
                                </div>

                                <!-- GraphQL编辑器 -->
                                <div id="graphql-editor" class="hidden">
                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Query</label>
                                        <textarea 
                                            id="graphql-query" 
                                            class="w-full h-32 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
                                            placeholder="输入GraphQL查询..."
                                        ></textarea>
                                    </div>
                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Variables (JSON)</label>
                                        <textarea 
                                            id="graphql-variables" 
                                            class="w-full h-24 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
                                            placeholder='{"id": 1}'
                                        ></textarea>
                                    </div>
                                </div>

                                <!-- 文件上传 -->
                                <div id="file-upload" class="hidden">
                                    <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                                        <input type="file" id="file-input" class="hidden" />
                                        <button id="select-file" class="bg-blue-100 hover:bg-blue-200 text-blue-700 px-4 py-2 rounded transition-colors">
                                            <i data-feather="upload" class="w-4 h-4 mr-2 inline"></i>
                                            选择文件
                                        </button>
                                        <p class="text-sm text-gray-500 mt-2">或拖拽文件到此处</p>
                                        <div id="file-info" class="mt-2 text-sm text-gray-600 hidden"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 认证面板 -->
                    <div id="panel-auth" class="tab-panel hidden">
                        <div class="mb-4">
                            <h4 class="font-medium text-gray-700 mb-4">认证方式</h4>
                            <select 
                                id="auth-type" 
                                class="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500 mb-4"
                            >
                                <option value="none">无认证</option>
                                <option value="bearer">Bearer Token</option>
                                <option value="basic">基础认证</option>
                                <option value="api-key">API Key</option>
                                <option value="oauth2">OAuth 2.0</option>
                            </select>
                            <div id="auth-fields"></div>
                        </div>
                    </div>

                    <!-- 参数面板 -->
                    <div id="panel-params" class="tab-panel hidden">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="font-medium text-gray-700">查询参数</h4>
                                <button 
                                    id="add-param" 
                                    class="text-green-600 hover:text-green-700 text-sm flex items-center"
                                >
                                    <i data-feather="plus" class="w-4 h-4 mr-1"></i>
                                    添加参数
                                </button>
                            </div>
                            <div id="params-container" class="space-y-2"></div>
                        </div>
                    </div>

                    <!-- 前置脚本面板 -->
                    <div id="panel-pre-script" class="tab-panel hidden">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="font-medium text-gray-700">前置脚本 (JavaScript)</h4>
                                <div class="flex gap-2">
                                    <button id="pre-script-help" class="text-blue-600 hover:text-blue-700 text-sm">
                                        <i data-feather="help-circle" class="w-4 h-4"></i>
                                    </button>
                                    <button id="pre-script-templates" class="text-green-600 hover:text-green-700 text-sm">
                                        <i data-feather="code" class="w-4 h-4"></i> 模板
                                    </button>
                                </div>
                            </div>
                            <textarea 
                                id="pre-request-script" 
                                class="w-full h-40 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
                                placeholder="// 在请求发送前执行的JavaScript代码
// 可以设置环境变量、全局变量等
// pm.environment.set('token', 'your-token');
// pm.globals.set('timestamp', Date.now());"
                            ></textarea>
                        </div>
                    </div>

                    <!-- 测试脚本面板 -->
                    <div id="panel-tests" class="tab-panel hidden">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="font-medium text-gray-700">测试脚本 (JavaScript)</h4>
                                <div class="flex gap-2">
                                    <button id="test-script-help" class="text-blue-600 hover:text-blue-700 text-sm">
                                        <i data-feather="help-circle" class="w-4 h-4"></i>
                                    </button>
                                    <button id="test-script-templates" class="text-green-600 hover:text-green-700 text-sm">
                                        <i data-feather="code" class="w-4 h-4"></i> 模板
                                    </button>
                                </div>
                            </div>
                            <textarea 
                                id="test-script" 
                                class="w-full h-40 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
                                placeholder="// 响应接收后执行的JavaScript代码
// 可以进行断言测试
// pm.test('Status code is 200', function () {
//     pm.response.to.have.status(200);
// });
// pm.test('Response has data', function () {
//     const jsonData = pm.response.json();
//     pm.expect(jsonData).to.have.property('data');
// });"
                            ></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 响应区域 -->
            <div class="bg-white rounded-xl shadow-sm border mb-6" id="response-section" style="display: none;">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold text-gray-700">响应结果</h3>
                        <div class="flex gap-2">
                            <button 
                                id="format-response" 
                                class="text-blue-600 hover:text-blue-700 text-sm flex items-center"
                            >
                                <i data-feather="align-left" class="w-4 h-4 mr-1"></i>
                                格式化
                            </button>
                            <button 
                                id="copy-response" 
                                class="text-gray-600 hover:text-gray-700 text-sm flex items-center"
                            >
                                <i data-feather="copy" class="w-4 h-4 mr-1"></i>
                                复制
                            </button>
                            <button 
                                id="download-response" 
                                class="text-purple-600 hover:text-purple-700 text-sm flex items-center"
                            >
                                <i data-feather="download" class="w-4 h-4 mr-1"></i>
                                下载
                            </button>
                        </div>
                    </div>

                    <!-- 响应状态 -->
                    <div class="flex items-center gap-4 mb-4 p-3 bg-gray-50 rounded-lg">
                        <div id="status-badge" class="px-3 py-1 rounded-full text-sm font-medium"></div>
                        <div class="text-sm text-gray-600">
                            <span id="response-time">0ms</span> | 
                            <span id="response-size">0 B</span>
                        </div>
                    </div>

                    <!-- 测试结果 -->
                    <div id="test-results" class="hidden mb-4">
                        <div class="p-3 bg-blue-50 rounded-lg">
                            <h4 class="font-medium text-blue-800 mb-2">测试结果</h4>
                            <div id="test-results-content"></div>
                        </div>
                    </div>

                    <!-- 响应选项卡 -->
                    <div class="border-b border-gray-200 mb-4">
                        <nav class="-mb-px flex space-x-8">
                            <button id="resp-tab-body" class="resp-tab-button py-2 px-1 border-b-2 border-green-500 font-medium text-sm text-green-600">
                                响应体
                            </button>
                            <button id="resp-tab-headers" class="resp-tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700">
                                响应头
                            </button>
                            <button id="resp-tab-cookies" class="resp-tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700">
                                Cookies
                            </button>
                            <button id="resp-tab-performance" class="resp-tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700">
                                性能分析
                            </button>
                        </nav>
                    </div>

                    <!-- 响应体 -->
                    <div id="resp-panel-body" class="resp-tab-panel">
                        <!-- 格式化工具栏 -->
                        <div class="mb-3 flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <label class="text-xs text-gray-600">格式:</label>
                                <select id="response-format" class="px-2 py-1 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500">
                                    <option value="auto">自动检测</option>
                                    <option value="json">JSON</option>
                                    <option value="xml">XML</option>
                                    <option value="html">HTML</option>
                                    <option value="csv">CSV</option>
                                    <option value="text">纯文本</option>
                                </select>
                                <button id="reformat-response" class="px-2 py-1 text-xs bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors" title="重新格式化">
                                    <i data-feather="refresh-cw" class="w-3 h-3"></i>
                                </button>
                            </div>
                            <div class="flex items-center gap-2">
                                <div id="response-stats" class="text-xs text-gray-500"></div>
                                <button id="copy-response" class="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded transition-colors" title="复制内容">
                                    <i data-feather="copy" class="w-3 h-3"></i>
                                </button>
                                <button id="download-response" class="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded transition-colors" title="下载内容">
                                    <i data-feather="download" class="w-3 h-3"></i>
                                </button>
                            </div>
                        </div>
                        <!-- 响应内容区域 -->
                        <div id="response-body" class="bg-gray-50 border rounded-lg p-4 max-h-96 overflow-auto text-sm font-mono whitespace-pre-wrap"></div>
                    </div>

                    <!-- 响应头 -->
                    <div id="resp-panel-headers" class="resp-tab-panel hidden">
                        <div id="response-headers" class="bg-gray-50 border rounded-lg p-4 max-h-96 overflow-auto text-sm font-mono"></div>
                    </div>

                    <!-- Cookies -->
                    <div id="resp-panel-cookies" class="resp-tab-panel hidden">
                        <div id="response-cookies" class="bg-gray-50 border rounded-lg p-4 max-h-96 overflow-auto text-sm"></div>
                    </div>

                    <!-- 性能分析 -->
                    <div id="resp-panel-performance" class="resp-tab-panel hidden">
                        <div id="performance-metrics" class="grid grid-cols-2 md:grid-cols-4 gap-4"></div>
                    </div>
                </div>
            </div>

            <!-- 请求历史和集合 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- 请求历史 -->
                <div class="bg-white rounded-xl shadow-sm border">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-semibold text-gray-700">请求历史</h3>
                            <div class="flex gap-2">
                                <button 
                                    id="export-history" 
                                    class="text-purple-600 hover:text-purple-700 text-sm flex items-center"
                                >
                                    <i data-feather="download" class="w-4 h-4 mr-1"></i>
                                    导出
                                </button>
                                <button 
                                    id="clear-history" 
                                    class="text-red-600 hover:text-red-700 text-sm flex items-center"
                                >
                                    <i data-feather="trash-2" class="w-4 h-4 mr-1"></i>
                                    清空
                                </button>
                            </div>
                        </div>
                        <div id="history-container" class="space-y-2 max-h-64 overflow-y-auto">
                            <div class="text-center text-gray-500 py-8">
                                <i data-feather="clock" class="w-12 h-12 mx-auto mb-2 text-gray-300"></i>
                                <p>暂无请求历史</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 请求集合 -->
                <div class="bg-white rounded-xl shadow-sm border">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-semibold text-gray-700">请求集合</h3>
                            <div class="flex gap-2">
                                <button 
                                    id="create-collection" 
                                    class="text-green-600 hover:text-green-700 text-sm flex items-center"
                                >
                                    <i data-feather="plus" class="w-4 h-4 mr-1"></i>
                                    新建
                                </button>
                                <button 
                                    id="import-collection" 
                                    class="text-blue-600 hover:text-blue-700 text-sm flex items-center"
                                >
                                    <i data-feather="upload" class="w-4 h-4 mr-1"></i>
                                    导入
                                </button>
                            </div>
                        </div>
                        <div id="collections-container" class="space-y-2 max-h-64 overflow-y-auto">
                            <div class="text-center text-gray-500 py-8">
                                <i data-feather="folder" class="w-12 h-12 mx-auto mb-2 text-gray-300"></i>
                                <p>暂无请求集合</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 模态框们 -->
            ${this.getModalsHTML()}

            <style>
                /* 选项卡样式 */
                .tab-button.active {
                    border-color: #059669;
                    color: #059669;
                }

                .resp-tab-button.active {
                    border-color: #059669;
                    color: #059669;
                }

                /* 状态徽章样式 */
                .status-success { background-color: #d1fae5; color: #065f46; }
                .status-warning { background-color: #fef3c7; color: #92400e; }
                .status-error { background-color: #fecaca; color: #991b1b; }
                .status-info { background-color: #dbeafe; color: #1e40af; }

                /* 请求历史项样式 */
                .history-item, .collection-item {
                    transition: all 0.2s;
                    cursor: pointer;
                }

                .history-item:hover, .collection-item:hover {
                    background-color: #f9fafb;
                    border-color: #059669;
                }

                /* 加载动画 */
                @keyframes spin {
                    to { transform: rotate(360deg); }
                }

                .loading-spinner {
                    animation: spin 1s linear infinite;
                }

                /* 响应体语法高亮 */
                .json-key { color: #0969da; font-weight: 600; }
                .json-string { color: #032f62; }
                .json-number { color: #cf222e; font-weight: 500; }
                .json-boolean { color: #8250df; font-weight: 500; }
                .json-null { color: #656d76; font-style: italic; }
                
                /* XML语法高亮 */
                .xml-tag { color: #0969da; }
                .xml-attr-name { color: #8250df; }
                .xml-attr-value { color: #032f62; }
                
                /* HTML语法高亮 */
                .html-tag { color: #0969da; }
                .html-tag-name { color: #cf222e; font-weight: 600; }
                .html-attr-name { color: #8250df; }
                .html-attr-value { color: #032f62; }
                .html-doctype { color: #656d76; font-style: italic; }
                
                /* 响应内容样式 */
                .response-content { 
                    margin: 0; 
                    padding: 0; 
                    background: transparent;
                    line-height: 1.5;
                }
                
                .json-content { font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; }
                .xml-content { font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; }  
                .html-content { font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; }
                .csv-content { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
                .text-content { font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; }
                
                /* CSV表格样式 */
                .csv-table-container { 
                    max-height: 400px; 
                    overflow: auto; 
                    border: 1px solid #e5e7eb;
                    border-radius: 6px;
                }

                /* 测试结果样式 */
                .test-passed { color: #059669; }
                .test-failed { color: #dc2626; }
                
                /* 拖拽区域样式 */
                .drag-over {
                    border-color: #059669;
                    background-color: #ecfdf5;
                }

                /* 环境变量高亮 */
                .variable-highlight {
                    background-color: #fef3c7;
                    color: #92400e;
                    padding: 1px 4px;
                    border-radius: 3px;
                    font-weight: 500;
                }
            </style>
        `;
    }

    static getModalsHTML() {
        return `
            <!-- 环境管理弹窗 -->
            <div id="environment-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-96 overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">环境管理</h3>
                        <button id="close-env-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div class="mb-4">
                        <button id="add-environment" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded">
                            <i data-feather="plus" class="w-4 h-4 mr-2 inline"></i>
                            添加环境
                        </button>
                    </div>
                    <div id="environments-list"></div>
                </div>
            </div>

            <!-- 代码生成器弹窗 -->
            <div id="code-generator-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-6xl w-full mx-4 max-h-[90vh] flex flex-col">
                    <div class="flex items-center justify-between mb-4 flex-shrink-0">
                        <h3 class="text-lg font-semibold">代码生成器</h3>
                        <button id="close-code-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div class="mb-4 flex-shrink-0">
                        <div class="flex flex-wrap items-center gap-3 mb-3">
                            <div class="flex items-center gap-2">
                                <label class="text-sm font-medium text-gray-700">选择语言:</label>
                                <select id="code-language" class="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500 text-sm">
                                    <option value="curl">cURL</option>
                                    <option value="javascript">JavaScript (Fetch)</option>
                                    <option value="javascript-axios">JavaScript (Axios)</option>
                                    <option value="javascript-jquery">JavaScript (jQuery)</option>
                                    <option value="python">Python (Requests)</option>
                                    <option value="python-urllib">Python (urllib)</option>
                                    <option value="nodejs">Node.js (HTTP)</option>
                                    <option value="nodejs-axios">Node.js (Axios)</option>
                                    <option value="php">PHP (cURL)</option>
                                    <option value="php-guzzle">PHP (Guzzle)</option>
                                    <option value="java">Java (OkHttp)</option>
                                    <option value="csharp">C# (HttpClient)</option>
                                    <option value="go">Go (net/http)</option>
                                    <option value="ruby">Ruby (Net::HTTP)</option>
                                    <option value="swift">Swift (URLSession)</option>
                                    <option value="kotlin">Kotlin (OkHttp)</option>
                                </select>
                            </div>
                            <button id="generate-code" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm flex items-center">
                                <i data-feather="code" class="w-4 h-4 mr-2"></i>
                                生成代码
                            </button>
                            <button id="copy-code" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded text-sm flex items-center">
                                <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                                复制
                            </button>
                            <button id="download-code" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded text-sm flex items-center">
                                <i data-feather="download" class="w-4 h-4 mr-2"></i>
                                下载
                            </button>
                        </div>
                        <div class="text-xs text-gray-500">
                            <span id="code-stats">代码行数: 0 | 字符数: 0</span>
                        </div>
                    </div>
                    <div class="flex-1 min-h-0">
                        <pre id="generated-code" class="bg-gray-50 border rounded p-4 h-full overflow-auto text-sm font-mono resize-none"></pre>
                    </div>
                </div>
            </div>

            <!-- 性能分析弹窗 -->
            <div id="performance-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-4xl w-full mx-4 max-h-96">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">性能分析报告</h3>
                        <button id="close-perf-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div id="performance-report"></div>
                </div>
            </div>

            <!-- 批量运行弹窗 -->
            <div id="collection-runner-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-96">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">批量运行集合</h3>
                        <button id="close-runner-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择集合:</label>
                        <select id="collection-to-run" class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500">
                            <option value="">选择要运行的集合...</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">运行环境:</label>
                        <select id="runner-environment" class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-green-500">
                            <option value="">使用当前环境</option>
                        </select>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button id="cancel-runner" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button id="start-runner" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded">开始运行</button>
                    </div>
                    <div id="runner-results" class="hidden mt-4"></div>
                </div>
            </div>

            <!-- cURL导入弹窗 -->
            <div id="curl-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-96">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">导入cURL命令</h3>
                        <button id="close-curl-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <textarea 
                        id="curl-input" 
                        class="w-full h-32 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
                        placeholder="粘贴cURL命令...支持多行格式"
                    ></textarea>
                    <div class="flex justify-end gap-2 mt-4">
                        <button id="cancel-curl" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button id="import-curl-confirm" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded">导入</button>
                    </div>
                </div>
            </div>

            <!-- 脚本模板选择弹窗 -->
            <div id="script-templates-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-3xl w-full mx-4 max-h-96">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">脚本模板</h3>
                        <button id="close-script-templates-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="script-templates-list"></div>
                </div>
            </div>

            <!-- 帮助信息弹窗 -->
            <div id="help-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
                <div class="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-96 overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">使用帮助</h3>
                        <button id="close-help-modal" class="text-gray-400 hover:text-gray-600">
                            <i data-feather="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                    <div id="help-content"></div>
                </div>
            </div>
        `;
    }

    static init() {
        console.log('API Tester Enhanced Renderer initializing...');
        
        // DOM 元素获取
        const httpMethod = document.getElementById('http-method');
        const requestUrl = document.getElementById('request-url');
        const sendBtn = document.getElementById('send-request');
        const templateSelect = document.getElementById('template-select');
        const clearAllBtn = document.getElementById('clear-all');
        
        // 选项卡相关
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabPanels = document.querySelectorAll('.tab-panel');
        const respTabButtons = document.querySelectorAll('.resp-tab-button');
        const respTabPanels = document.querySelectorAll('.resp-tab-panel');
        
        // 请求配置相关
        const headersContainer = document.getElementById('headers-container');
        const addHeaderBtn = document.getElementById('add-header');
        const bodyType = document.getElementById('body-type');
        const bodyText = document.getElementById('body-text');
        const authType = document.getElementById('auth-type');
        const authFields = document.getElementById('auth-fields');
        const paramsContainer = document.getElementById('params-container');
        const addParamBtn = document.getElementById('add-param');
        
        // 响应相关
        const responseSection = document.getElementById('response-section');
        const statusBadge = document.getElementById('status-badge');
        const responseTime = document.getElementById('response-time');
        const responseSize = document.getElementById('response-size');
        const responseBody = document.getElementById('response-body');
        const responseHeaders = document.getElementById('response-headers');
        const formatResponseBtn = document.getElementById('format-response');
        const copyResponseBtn = document.getElementById('copy-response');
        const downloadResponseBtn = document.getElementById('download-response');
        
        // 历史记录相关
        const historyContainer = document.getElementById('history-container');
        const exportHistoryBtn = document.getElementById('export-history');
        const clearHistoryBtn = document.getElementById('clear-history');
        const saveRequestBtn = document.getElementById('save-request');
        
        // cURL相关
        const importCurlBtn = document.getElementById('import-curl');
        const exportCurlBtn = document.getElementById('export-curl');
        const curlModal = document.getElementById('curl-modal');
        const closeCurlModal = document.getElementById('close-curl-modal');
        const curlInput = document.getElementById('curl-input');
        const importCurlConfirm = document.getElementById('import-curl-confirm');
        const cancelCurl = document.getElementById('cancel-curl');
        
        // 高级功能按钮
        const codeGeneratorBtn = document.getElementById('code-generator');
        const performanceAnalyzerBtn = document.getElementById('performance-analyzer');
        const runCollectionBtn = document.getElementById('run-collection');
        const manageEnvironmentsBtn = document.getElementById('manage-environments');
        
        // 全局状态
        let currentResponse = null;
        
        // 初始化函数
        const initializeRenderer = () => {
            loadHistory();
            loadEnvironments();
            setupEventListeners();
            
            // 初始化默认请求头
            if (headersContainer && headersContainer.children.length === 0) {
                addHeaderRow('Content-Type', 'application/json');
            }
        };
        
        // 设置事件监听器
        const setupEventListeners = () => {
            // 发送请求
            if (sendBtn) {
                sendBtn.addEventListener('click', handleSendRequest);
            }
            
            // 选项卡切换
            tabButtons.forEach(button => {
                button.addEventListener('click', () => switchTab(button.id.replace('tab-', '')));
            });
            
            respTabButtons.forEach(button => {
                button.addEventListener('click', () => switchRespTab(button.id.replace('resp-tab-', '')));
            });

            // 响应格式化功能
            const responseFormat = document.getElementById('response-format');
            const reformatBtn = document.getElementById('reformat-response');
            const copyResponseBtn = document.getElementById('copy-response');
            const downloadResponseBtn = document.getElementById('download-response');

            if (responseFormat) {
                responseFormat.addEventListener('change', () => {
                    if (currentResponse && currentResponse.response.body) {
                        displayFormattedResponse(currentResponse.response.body);
                    }
                });
            }

            if (reformatBtn) {
                reformatBtn.addEventListener('click', () => {
                    if (currentResponse && currentResponse.response.body) {
                        displayFormattedResponse(currentResponse.response.body);
                        DevToolsUtils.showToast('响应已重新格式化', 'success');
                    } else {
                        DevToolsUtils.showToast('没有响应内容可以格式化', 'warning');
                    }
                });
            }

            if (copyResponseBtn) {
                copyResponseBtn.addEventListener('click', copyResponseContent);
            }

            if (downloadResponseBtn) {
                downloadResponseBtn.addEventListener('click', downloadResponseContent);
            }
            
            // cURL 功能
            if (importCurlBtn) importCurlBtn.addEventListener('click', () => showModal('curl-modal'));
            if (exportCurlBtn) exportCurlBtn.addEventListener('click', handleExportCurl);
            if (closeCurlModal) closeCurlModal.addEventListener('click', () => hideModal('curl-modal'));
            if (cancelCurl) cancelCurl.addEventListener('click', () => hideModal('curl-modal'));
            if (importCurlConfirm) importCurlConfirm.addEventListener('click', handleImportCurl);
            
            // 请求头管理
            if (addHeaderBtn) addHeaderBtn.addEventListener('click', () => addHeaderRow());
            if (headersContainer) {
                headersContainer.addEventListener('click', (e) => {
                    if (e.target.closest('.remove-header')) {
                        e.target.closest('.header-row').remove();
                    }
                });
            }
            
            // 请求体类型切换
            if (bodyType) bodyType.addEventListener('change', handleBodyTypeChange);
            
            // JSON工具栏功能
            const formatJsonBtn = document.getElementById('format-json');
            const minifyJsonBtn = document.getElementById('minify-json');
            const validateJsonBtn = document.getElementById('validate-json');
            
            if (formatJsonBtn) {
                formatJsonBtn.addEventListener('click', formatJsonBody);
            }
            
            if (minifyJsonBtn) {
                minifyJsonBtn.addEventListener('click', minifyJsonBody);
            }
            
            if (validateJsonBtn) {
                validateJsonBtn.addEventListener('click', validateJsonBody);
            }
            
            // 请求体字符统计
            if (bodyText) {
                bodyText.addEventListener('input', updateBodyStats);
            }
            
            // 认证类型切换
            if (authType) authType.addEventListener('change', handleAuthTypeChange);
            
            // 参数管理
            if (addParamBtn) addParamBtn.addEventListener('click', () => addParamRow());
            if (paramsContainer) {
                paramsContainer.addEventListener('click', (e) => {
                    if (e.target.closest('.remove-param')) {
                        e.target.closest('.param-row').remove();
                    }
                });
            }
            
            // 表单字段管理
            const addFormFieldBtn = document.getElementById('add-form-field');
            const bulkAddFieldsBtn = document.getElementById('bulk-add-fields');
            const formContainer = document.getElementById('form-container');
            
            if (addFormFieldBtn) {
                addFormFieldBtn.addEventListener('click', () => addFormFieldRow());
            }
            
            if (bulkAddFieldsBtn) {
                bulkAddFieldsBtn.addEventListener('click', handleBulkAddFields);
            }
            
            if (formContainer) {
                formContainer.addEventListener('click', (e) => {
                    if (e.target.closest('.remove-form-field')) {
                        e.target.closest('.form-field-row').remove();
                    }
                });
            }
            
            // 文件上传功能
            const fileInput = document.getElementById('file-input');
            const selectFileBtn = document.getElementById('select-file');
            const fileUploadArea = document.getElementById('file-upload');
            
            if (selectFileBtn && fileInput) {
                selectFileBtn.addEventListener('click', () => fileInput.click());
            }
            
            if (fileInput) {
                fileInput.addEventListener('change', handleFileSelect);
            }
            
            if (fileUploadArea) {
                fileUploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    fileUploadArea.classList.add('drag-over');
                });
                
                fileUploadArea.addEventListener('dragleave', () => {
                    fileUploadArea.classList.remove('drag-over');
                });
                
                fileUploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    fileUploadArea.classList.remove('drag-over');
                    
                    const files = e.dataTransfer.files;
                    if (files.length > 0) {
                        handleFileSelect({ target: { files } });
                    }
                });
            }
            
            // 模板选择
            if (templateSelect) templateSelect.addEventListener('change', handleTemplateSelect);
            
            // 响应操作
            if (formatResponseBtn) formatResponseBtn.addEventListener('click', formatResponse);
            if (copyResponseBtn) copyResponseBtn.addEventListener('click', copyResponse);
            if (downloadResponseBtn) downloadResponseBtn.addEventListener('click', downloadResponse);
            
            // 历史记录
            if (exportHistoryBtn) exportHistoryBtn.addEventListener('click', exportHistory);
            if (clearHistoryBtn) clearHistoryBtn.addEventListener('click', clearHistory);
            if (saveRequestBtn) saveRequestBtn.addEventListener('click', saveCurrentRequest);
            
            // 清空所有
            if (clearAllBtn) clearAllBtn.addEventListener('click', clearAll);
            
            // 高级功能
            if (codeGeneratorBtn) {
                codeGeneratorBtn.addEventListener('click', () => {
                    showModal('code-generator-modal');
                    // 自动生成当前配置的代码
                    setTimeout(() => {
                        const generateBtn = document.getElementById('generate-code');
                        if (generateBtn) {
                            generateBtn.click();
                        }
                    }, 100);
                });
            }
            if (performanceAnalyzerBtn) performanceAnalyzerBtn.addEventListener('click', () => showModal('performance-modal'));
            if (runCollectionBtn) runCollectionBtn.addEventListener('click', () => showModal('collection-runner-modal'));
            if (manageEnvironmentsBtn) manageEnvironmentsBtn.addEventListener('click', () => showModal('environment-modal'));
            
            // 键盘快捷键
            document.addEventListener('keydown', (e) => {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    handleSendRequest();
                }
            });
        };
        
        // 切换选项卡
        const switchTab = (tabName) => {
            tabButtons.forEach(btn => {
                btn.classList.remove('active');
                btn.classList.add('text-gray-500', 'border-transparent');
                btn.classList.remove('text-green-600', 'border-green-500');
            });
            
            tabPanels.forEach(panel => panel.classList.add('hidden'));
            
            const activeButton = document.getElementById(`tab-${tabName}`);
            const activePanel = document.getElementById(`panel-${tabName}`);
            
            if (activeButton && activePanel) {
                activeButton.classList.add('active', 'text-green-600', 'border-green-500');
                activeButton.classList.remove('text-gray-500', 'border-transparent');
                activePanel.classList.remove('hidden');
            }
        };
        
        // 切换响应选项卡
        const switchRespTab = (tabName) => {
            respTabButtons.forEach(btn => {
                btn.classList.remove('active');
                btn.classList.add('text-gray-500', 'border-transparent');
                btn.classList.remove('text-green-600', 'border-green-500');
            });
            
            respTabPanels.forEach(panel => panel.classList.add('hidden'));
            
            const activeButton = document.getElementById(`resp-tab-${tabName}`);
            const activePanel = document.getElementById(`resp-panel-${tabName}`);
            
            if (activeButton && activePanel) {
                activeButton.classList.add('active', 'text-green-600', 'border-green-500');
                activeButton.classList.remove('text-gray-500', 'border-transparent');
                activePanel.classList.remove('hidden');
            }
        };
        
        // 发送请求
        const handleSendRequest = async () => {
            const config = getRequestConfig();
            if (!config.url.trim()) {
                DevToolsUtils.showToast('请输入请求URL', 'warning');
                return;
            }

            DevToolsUtils.addLoading(sendBtn);
            
            try {
                const result = await APITester.sendRequest(config);
                
                if (result.success) {
                    displayResponse(result.data);
                    APITester.saveToHistory(config, result.data.response);
                    loadHistory();
                    DevToolsUtils.showToast('请求发送成功', 'success');
                } else {
                    displayError(result.error, result.data);
                    DevToolsUtils.showToast(result.error, 'error');
                }
            } catch (error) {
                displayError('请求失败', { error: { message: error.message } });
                DevToolsUtils.showToast('请求失败', 'error');
            }
            
            DevToolsUtils.removeLoading(sendBtn);
        };
        
        // 获取请求配置
        const getRequestConfig = () => {
            const config = {
                url: requestUrl ? requestUrl.value.trim() : '',
                method: httpMethod ? httpMethod.value : 'GET',
                headers: {},
                body: null
            };

            // 收集请求头
            if (headersContainer) {
                const headerRows = headersContainer.querySelectorAll('.header-row');
                headerRows.forEach(row => {
                    const inputs = row.querySelectorAll('input');
                    if (inputs.length >= 2 && inputs[0].value.trim() && inputs[1].value.trim()) {
                        config.headers[inputs[0].value.trim()] = inputs[1].value.trim();
                    }
                });
            }

            // 收集认证信息
            if (authType && authType.value !== 'none') {
                const authInputs = authFields ? authFields.querySelectorAll('input') : [];
                
                switch (authType.value) {
                    case 'bearer':
                        if (authInputs[0] && authInputs[0].value.trim()) {
                            config.headers['Authorization'] = `Bearer ${authInputs[0].value.trim()}`;
                        }
                        break;
                    case 'basic':
                        if (authInputs[0] && authInputs[1] && authInputs[0].value.trim() && authInputs[1].value.trim()) {
                            const credentials = btoa(`${authInputs[0].value.trim()}:${authInputs[1].value.trim()}`);
                            config.headers['Authorization'] = `Basic ${credentials}`;
                        }
                        break;
                    case 'api-key':
                        if (authInputs[0] && authInputs[1] && authInputs[0].value.trim() && authInputs[1].value.trim()) {
                            config.headers[authInputs[0].value.trim()] = authInputs[1].value.trim();
                        }
                        break;
                }
            }

            // 收集查询参数
            if (paramsContainer) {
                const paramRows = paramsContainer.querySelectorAll('.param-row');
                const params = new URLSearchParams();
                paramRows.forEach(row => {
                    const inputs = row.querySelectorAll('input');
                    if (inputs.length >= 2 && inputs[0].value.trim() && inputs[1].value.trim()) {
                        params.append(inputs[0].value.trim(), inputs[1].value.trim());
                    }
                });
                
                if (params.toString()) {
                    const separator = config.url.includes('?') ? '&' : '?';
                    config.url += separator + params.toString();
                }
            }

            // 收集请求体
            if (bodyType && ['POST', 'PUT', 'PATCH'].includes(config.method)) {
                const bodyTypeValue = bodyType.value;
                if (bodyTypeValue !== 'none' && bodyText) {
                    switch (bodyTypeValue) {
                        case 'json':
                        case 'text':
                        case 'xml':
                            config.body = bodyText.value.trim();
                            break;
                    }
                }
            }

            return config;
        };
        
        // 显示响应
        const displayResponse = (data) => {
            currentResponse = data;
            const response = data.response;
            
            if (responseSection) {
                responseSection.style.display = 'block';
            }
            
            // 状态信息
            const statusInfo = APITester.getStatusInfo(response.status);
            if (statusBadge) {
                statusBadge.textContent = `${response.status} ${response.statusText}`;
                statusBadge.className = `px-3 py-1 rounded-full text-sm font-medium status-${statusInfo.type}`;
            }
            
            if (responseTime) responseTime.textContent = `${response.duration}ms`;
            if (responseSize) responseSize.textContent = DevToolsUtils.formatFileSize(response.size);
            
            // 格式化并显示响应体
            displayFormattedResponse(response.body || '');
            
            // 响应头
            if (responseHeaders) {
                const headersHtml = Object.entries(response.headers)
                    .map(([key, value]) => `<div><strong>${key}:</strong> ${value}</div>`)
                    .join('');
                responseHeaders.innerHTML = headersHtml || '(无响应头)';
            }
            
            // 显示Cookie信息
            displayCookies(response.headers);
            
            // 显示性能指标
            displayPerformanceMetrics(response);
            
            // 显示测试结果（如果有）
            if (data.tests) {
                displayTestResults(data.tests);
            }
        };

        // 格式化显示响应体
        const displayFormattedResponse = (content) => {
            if (!responseBody) return;
            
            if (!content || content.trim() === '') {
                responseBody.innerHTML = '<div class="text-gray-500 italic">(无响应体)</div>';
                updateResponseStats('', '');
                return;
            }
            
            // 获取选择的格式
            const responseFormat = document.getElementById('response-format');
            const selectedFormat = responseFormat ? responseFormat.value : 'auto';
            
            // 调用格式化方法
            const formatResult = APITester.formatResponse(content, selectedFormat);
            
            if (formatResult.success) {
                // 显示格式化后的内容
                responseBody.innerHTML = `<pre class="response-content ${formatResult.type}-content">${formatResult.data}</pre>`;
                updateResponseStats(formatResult, selectedFormat);
            } else {
                // 格式化失败，显示原始内容
                responseBody.innerHTML = `
                    <div class="mb-2 p-2 bg-red-50 border border-red-200 rounded text-red-600 text-sm">
                        格式化失败: ${formatResult.error}
                    </div>
                    <pre class="response-content text-content">${APITester.escapeHtml(content)}</pre>
                `;
                updateResponseStats({ type: 'text', size: content.length, lines: content.split('\n').length }, selectedFormat);
            }
        };

        // 更新响应统计信息
        const updateResponseStats = (formatResult, selectedFormat) => {
            const responseStats = document.getElementById('response-stats');
            if (!responseStats) return;
            
            if (!formatResult || formatResult === '') {
                responseStats.innerHTML = '';
                return;
            }
            
            let statsHtml = `
                <div class="text-xs text-gray-500 space-x-4">
                    <span>格式: ${getFormatDisplayName(formatResult.type || selectedFormat)}</span>
                    <span>大小: ${DevToolsUtils.formatFileSize(formatResult.size || 0)}</span>
                    <span>行数: ${formatResult.lines || 0}</span>
            `;
            
            // CSV特殊统计
            if (formatResult.type === 'csv' && formatResult.rows && formatResult.columns) {
                statsHtml += `<span>行: ${formatResult.rows}</span><span>列: ${formatResult.columns}</span>`;
            }
            
            statsHtml += '</div>';
            responseStats.innerHTML = statsHtml;
        };

        // 获取格式显示名称
        const getFormatDisplayName = (format) => {
            const names = {
                'json': 'JSON',
                'xml': 'XML', 
                'html': 'HTML',
                'csv': 'CSV',
                'text': '纯文本',
                'auto': '自动检测'
            };
            return names[format] || format.toUpperCase();
        };

        // 复制响应内容
        const copyResponseContent = () => {
            if (!currentResponse || !currentResponse.response.body) {
                DevToolsUtils.showToast('没有可复制的响应内容', 'warning');
                return;
            }
            
            const responseFormat = document.getElementById('response-format');
            const selectedFormat = responseFormat ? responseFormat.value : 'auto';
            const formatResult = APITester.formatResponse(currentResponse.response.body, selectedFormat);
            
            const contentToCopy = formatResult.success && formatResult.raw ? formatResult.raw : currentResponse.response.body;
            
            DevToolsUtils.copyToClipboard(contentToCopy);
            DevToolsUtils.showToast('响应内容已复制到剪贴板', 'success');
        };

        // 下载响应内容
        const downloadResponseContent = () => {
            if (!currentResponse || !currentResponse.response.body) {
                DevToolsUtils.showToast('没有可下载的响应内容', 'warning');
                return;
            }
            
            const responseFormat = document.getElementById('response-format');
            const selectedFormat = responseFormat ? responseFormat.value : 'auto';
            const formatResult = APITester.formatResponse(currentResponse.response.body, selectedFormat);
            
            const contentToDownload = formatResult.success && formatResult.raw ? formatResult.raw : currentResponse.response.body;
            const fileType = formatResult.success ? formatResult.type : 'txt';
            
            const extensions = {
                'json': 'json',
                'xml': 'xml',
                'html': 'html', 
                'csv': 'csv',
                'text': 'txt'
            };
            
            const extension = extensions[fileType] || 'txt';
            const filename = `response.${extension}`;
            const mimeTypes = {
                'json': 'application/json',
                'xml': 'application/xml',
                'html': 'text/html',
                'csv': 'text/csv',
                'text': 'text/plain'
            };
            
            const mimeType = mimeTypes[fileType] || 'text/plain';
            const blob = new Blob([contentToDownload], { type: mimeType });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            
            URL.revokeObjectURL(url);
            DevToolsUtils.showToast(`响应已下载为 ${filename}`, 'success');
        };
        
        // 显示Cookie信息
        const displayCookies = (headers) => {
            const responseCookies = document.getElementById('response-cookies');
            if (!responseCookies) return;
            
            // 从响应头中提取Cookie信息
            const cookieHeaders = [];
            Object.entries(headers).forEach(([key, value]) => {
                if (key.toLowerCase() === 'set-cookie') {
                    cookieHeaders.push(value);
                }
            });
            
            if (cookieHeaders.length > 0) {
                let cookiesHtml = '<div class="space-y-2">';
                cookieHeaders.forEach((cookieValue, index) => {
                    const cookies = Array.isArray(cookieValue) ? cookieValue : [cookieValue];
                    cookies.forEach(cookie => {
                        const parts = cookie.split(';').map(part => part.trim());
                        const [nameValue, ...attributes] = parts;
                        const [name, value] = nameValue.split('=');
                        
                        cookiesHtml += `
                            <div class="border rounded p-3 bg-gray-50">
                                <div class="font-semibold text-sm text-gray-800">${name || 'Unknown'}</div>
                                <div class="text-xs text-gray-600 mt-1">值: ${value || 'N/A'}</div>
                                ${attributes.length > 0 ? `<div class="text-xs text-gray-500 mt-1">属性: ${attributes.join(', ')}</div>` : ''}
                            </div>
                        `;
                    });
                });
                cookiesHtml += '</div>';
                responseCookies.innerHTML = cookiesHtml;
            } else {
                responseCookies.innerHTML = '<div class="text-center text-gray-500 py-4">此响应未设置Cookie</div>';
            }
        };
        
        // 显示性能指标
        const displayPerformanceMetrics = (response) => {
            const performanceMetrics = document.getElementById('performance-metrics');
            if (!performanceMetrics) return;
            
            // 计算各种性能指标
            const metrics = {
                responseTime: response.duration || 0,
                responseSize: response.size || 0,
                status: response.status || 0,
                contentType: getHeaderValue(response.headers, 'content-type') || 'unknown'
            };
            
            // 性能评估
            const getPerformanceLevel = (time) => {
                if (time < 200) return { level: '极快', color: 'text-green-600', bg: 'bg-green-50' };
                if (time < 500) return { level: '快速', color: 'text-blue-600', bg: 'bg-blue-50' };
                if (time < 1000) return { level: '正常', color: 'text-yellow-600', bg: 'bg-yellow-50' };
                if (time < 3000) return { level: '较慢', color: 'text-orange-600', bg: 'bg-orange-50' };
                return { level: '慢', color: 'text-red-600', bg: 'bg-red-50' };
            };
            
            const getSizeLevel = (size) => {
                if (size < 1024) return { level: '很小', color: 'text-green-600' };
                if (size < 10240) return { level: '小', color: 'text-blue-600' };
                if (size < 102400) return { level: '中等', color: 'text-yellow-600' };
                if (size < 1048576) return { level: '大', color: 'text-orange-600' };
                return { level: '很大', color: 'text-red-600' };
            };
            
            const perfLevel = getPerformanceLevel(metrics.responseTime);
            const sizeLevel = getSizeLevel(metrics.responseSize);
            
            performanceMetrics.innerHTML = `
                <div class="p-4 ${perfLevel.bg} rounded-lg">
                    <div class="text-sm font-medium text-gray-700">响应时间</div>
                    <div class="text-2xl font-bold ${perfLevel.color}">${metrics.responseTime}ms</div>
                    <div class="text-xs ${perfLevel.color}">${perfLevel.level}</div>
                </div>
                <div class="p-4 bg-blue-50 rounded-lg">
                    <div class="text-sm font-medium text-gray-700">响应大小</div>
                    <div class="text-2xl font-bold text-blue-600">${DevToolsUtils.formatFileSize(metrics.responseSize)}</div>
                    <div class="text-xs ${sizeLevel.color}">${sizeLevel.level}</div>
                </div>
                <div class="p-4 bg-purple-50 rounded-lg">
                    <div class="text-sm font-medium text-gray-700">状态码</div>
                    <div class="text-2xl font-bold text-purple-600">${metrics.status}</div>
                    <div class="text-xs text-purple-600">${APITester.getStatusInfo(metrics.status).message}</div>
                </div>
                <div class="p-4 bg-gray-50 rounded-lg">
                    <div class="text-sm font-medium text-gray-700">内容类型</div>
                    <div class="text-sm font-bold text-gray-600">${metrics.contentType.split(';')[0]}</div>
                    <div class="text-xs text-gray-500">编码: ${metrics.contentType.includes('charset=') ? metrics.contentType.split('charset=')[1] : 'UTF-8'}</div>
                </div>
            `;
        };
        
        // 显示测试结果
        const displayTestResults = (tests) => {
            const testResults = document.getElementById('test-results');
            const testResultsContent = document.getElementById('test-results-content');
            
            if (!testResults || !testResultsContent || !tests || Object.keys(tests).length === 0) {
                if (testResults) testResults.classList.add('hidden');
                return;
            }
            
            testResults.classList.remove('hidden');
            
            const testEntries = Object.entries(tests);
            const passed = testEntries.filter(([, result]) => result.status === 'passed').length;
            const failed = testEntries.filter(([, result]) => result.status === 'failed').length;
            
            let html = `
                <div class="flex items-center gap-4 mb-3">
                    <div class="text-sm">
                        总计: ${testEntries.length} | 
                        <span class="text-green-600">通过: ${passed}</span> | 
                        <span class="text-red-600">失败: ${failed}</span>
                    </div>
                </div>
                <div class="space-y-2">
            `;
            
            testEntries.forEach(([testName, result]) => {
                const statusColor = result.status === 'passed' ? 'text-green-600' : 'text-red-600';
                const statusIcon = result.status === 'passed' ? '✓' : '✗';
                
                html += `
                    <div class="flex items-start gap-2 text-sm">
                        <span class="${statusColor} font-bold">${statusIcon}</span>
                        <div class="flex-1">
                            <div class="font-medium">${testName}</div>
                            ${result.error ? `<div class="text-red-500 text-xs mt-1">${result.error}</div>` : ''}
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            testResultsContent.innerHTML = html;
        };
        
        // 获取响应头值的辅助函数
        const getHeaderValue = (headers, name) => {
            const key = Object.keys(headers).find(k => k.toLowerCase() === name.toLowerCase());
            return key ? headers[key] : null;
        };
        
        // 显示错误
        const displayError = (message, data) => {
            if (responseSection) {
                responseSection.style.display = 'block';
            }
            
            if (statusBadge) {
                statusBadge.textContent = 'ERROR';
                statusBadge.className = 'px-3 py-1 rounded-full text-sm font-medium status-error';
            }
            
            if (responseTime) responseTime.textContent = '-';
            if (responseSize) responseSize.textContent = '-';
            
            if (responseBody) responseBody.textContent = `错误: ${message}`;
            if (responseHeaders) responseHeaders.innerHTML = data?.error?.message || '';
        };
        
        // 添加请求头行
        const addHeaderRow = (key = '', value = '') => {
            if (!headersContainer) return;
            
            const row = document.createElement('div');
            row.className = 'flex gap-2 header-row';
            row.innerHTML = `
                <input type="text" placeholder="Header名称" class="flex-1 px-3 py-2 border border-gray-300 rounded header-name-input" value="${key}">
                <input type="text" placeholder="Header值" class="flex-1 px-3 py-2 border border-gray-300 rounded" value="${value}">
                <button class="text-red-500 hover:text-red-700 remove-header">
                    <i data-feather="x" class="w-4 h-4"></i>
                </button>
            `;
            headersContainer.appendChild(row);
            
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 10);
        };
        
        // 添加参数行
        const addParamRow = () => {
            if (!paramsContainer) return;
            
            const row = document.createElement('div');
            row.className = 'flex gap-2 param-row';
            row.innerHTML = `
                <input type="text" placeholder="参数名" class="flex-1 px-3 py-2 border border-gray-300 rounded">
                <input type="text" placeholder="参数值" class="flex-1 px-3 py-2 border border-gray-300 rounded">
                <button class="text-red-500 hover:text-red-700 remove-param">
                    <i data-feather="x" class="w-4 h-4"></i>
                </button>
            `;
            paramsContainer.appendChild(row);
            
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 10);
        };
        
        // 处理请求体类型变化
        const handleBodyTypeChange = () => {
            if (!bodyType || !bodyText) return;
            
            const type = bodyType.value;
            const jsonToolbar = document.getElementById('json-toolbar');
            const bodyStats = document.getElementById('body-stats');
            
            if (type === 'none') {
                bodyText.classList.add('hidden');
                if (jsonToolbar) jsonToolbar.classList.add('hidden');
                if (bodyStats) bodyStats.classList.add('hidden');
            } else {
                bodyText.classList.remove('hidden');
                if (bodyStats) bodyStats.classList.remove('hidden');
                
                // 显示JSON工具栏
                if (type === 'json') {
                    if (jsonToolbar) jsonToolbar.classList.remove('hidden');
                    if (!bodyText.value.trim()) {
                        bodyText.value = '{\n  "key": "value"\n}';
                    }
                } else {
                    if (jsonToolbar) jsonToolbar.classList.add('hidden');
                }
                
                updateBodyStats();
            }
        };
        
        // JSON格式化功能
        const formatJsonBody = () => {
            if (!bodyText) return;
            
            try {
                const jsonObject = JSON.parse(bodyText.value);
                bodyText.value = JSON.stringify(jsonObject, null, 2);
                showJsonStatus('success', 'JSON格式化成功');
                updateBodyStats();
                DevToolsUtils.showToast('JSON格式化成功', 'success');
            } catch (error) {
                showJsonStatus('error', `JSON格式错误: ${error.message}`);
                DevToolsUtils.showToast('JSON格式错误', 'error');
            }
        };
        
        // JSON压缩功能
        const minifyJsonBody = () => {
            if (!bodyText) return;
            
            try {
                const jsonObject = JSON.parse(bodyText.value);
                bodyText.value = JSON.stringify(jsonObject);
                showJsonStatus('success', 'JSON压缩成功');
                updateBodyStats();
                DevToolsUtils.showToast('JSON压缩成功', 'success');
            } catch (error) {
                showJsonStatus('error', `JSON格式错误: ${error.message}`);
                DevToolsUtils.showToast('JSON格式错误', 'error');
            }
        };
        
        // JSON验证功能
        const validateJsonBody = () => {
            if (!bodyText) return;
            
            try {
                JSON.parse(bodyText.value);
                showJsonStatus('success', 'JSON格式正确');
                DevToolsUtils.showToast('JSON格式正确', 'success');
            } catch (error) {
                showJsonStatus('error', `JSON格式错误: ${error.message}`);
                DevToolsUtils.showToast('JSON格式错误', 'error');
            }
        };
        
        // 显示JSON状态
        const showJsonStatus = (type, message) => {
            const jsonStatus = document.getElementById('json-status');
            const jsonStatusIcon = document.getElementById('json-status-icon');
            const jsonStatusText = document.getElementById('json-status-text');
            
            if (!jsonStatus || !jsonStatusIcon || !jsonStatusText) return;
            
            jsonStatus.classList.remove('hidden');
            
            if (type === 'success') {
                jsonStatusIcon.innerHTML = '<i data-feather="check-circle" class="w-4 h-4 text-green-600"></i>';
                jsonStatusText.className = 'text-green-600';
            } else if (type === 'error') {
                jsonStatusIcon.innerHTML = '<i data-feather="alert-circle" class="w-4 h-4 text-red-600"></i>';
                jsonStatusText.className = 'text-red-600';
            }
            
            jsonStatusText.textContent = message;
            
            // 更新图标
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 10);
            
            // 3秒后自动隐藏状态
            setTimeout(() => {
                if (jsonStatus) {
                    jsonStatus.classList.add('hidden');
                }
            }, 3000);
        };
        
        // 更新请求体统计信息
        const updateBodyStats = () => {
            if (!bodyText) return;
            
            const charCount = document.getElementById('char-count');
            const lineCount = document.getElementById('line-count');
            
            if (charCount) {
                charCount.textContent = bodyText.value.length;
            }
            
            if (lineCount) {
                lineCount.textContent = bodyText.value.split('\n').length;
            }
        };
        
        // 处理认证类型变化
        const handleAuthTypeChange = () => {
            if (!authType || !authFields) return;
            
            const type = authType.value;
            authFields.innerHTML = '';
            
            if (type === 'bearer') {
                authFields.innerHTML = `
                    <input type="text" placeholder="Bearer Token" class="w-full px-3 py-2 border border-gray-300 rounded">
                `;
            } else if (type === 'basic') {
                authFields.innerHTML = `
                    <div class="grid grid-cols-2 gap-2">
                        <input type="text" placeholder="用户名" class="px-3 py-2 border border-gray-300 rounded">
                        <input type="password" placeholder="密码" class="px-3 py-2 border border-gray-300 rounded">
                    </div>
                `;
            } else if (type === 'api-key') {
                authFields.innerHTML = `
                    <div class="grid grid-cols-2 gap-2">
                        <input type="text" placeholder="Header名称" class="px-3 py-2 border border-gray-300 rounded" value="X-API-Key">
                        <input type="text" placeholder="API Key值" class="px-3 py-2 border border-gray-300 rounded">
                    </div>
                `;
            }
        };

        // 表单字段管理
        const addFormFieldRow = (key = '', value = '', type = 'text', file = null) => {
            const formFieldsContainer = document.getElementById('form-fields-container');
            if (!formFieldsContainer) return;

            const fieldId = `field-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
            const fieldRow = document.createElement('div');
            fieldRow.className = 'form-field-row flex items-center space-x-2 mb-2';
            fieldRow.innerHTML = `
                <input type="text" placeholder="字段名" value="${key}" class="flex-1 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" data-role="field-key">
                <select class="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" data-role="field-type" onchange="toggleFieldInput(this)">
                    <option value="text" ${type === 'text' ? 'selected' : ''}>文本</option>
                    <option value="file" ${type === 'file' ? 'selected' : ''}>文件</option>
                </select>
                <div class="flex-2 field-input-container">
                    ${type === 'file' ? 
                        `<div class="flex items-center space-x-2">
                            <input type="file" class="hidden" id="${fieldId}" data-role="field-file">
                            <button type="button" onclick="document.getElementById('${fieldId}').click()" class="px-3 py-2 bg-gray-100 border border-gray-300 rounded hover:bg-gray-200">
                                ${file ? file.name : '选择文件'}
                            </button>
                            ${file ? `<span class="text-sm text-gray-500">(${DevToolsUtils.formatFileSize(file.size)})</span>` : ''}
                        </div>` : 
                        `<input type="text" placeholder="字段值" value="${value}" class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" data-role="field-value">`
                    }
                </div>
                <button type="button" onclick="this.parentElement.remove(); updateFormDataStats();" class="px-2 py-2 text-red-600 hover:text-red-800">
                    <i data-feather="trash-2" class="w-4 h-4"></i>
                </button>
            `;
            
            formFieldsContainer.appendChild(fieldRow);
            
            // 为文件输入添加事件监听器
            const fileInput = fieldRow.querySelector('[data-role="field-file"]');
            if (fileInput) {
                fileInput.addEventListener('change', (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const button = fieldRow.querySelector('button[onclick*="click"]');
                        const sizeSpan = fieldRow.querySelector('.text-gray-500');
                        if (button) {
                            button.textContent = file.name;
                        }
                        if (sizeSpan) {
                            sizeSpan.textContent = `(${DevToolsUtils.formatFileSize(file.size)})`;
                        } else {
                            const container = fieldRow.querySelector('.field-input-container > div');
                            container.insertAdjacentHTML('beforeend', `<span class="text-sm text-gray-500">(${DevToolsUtils.formatFileSize(file.size)})</span>`);
                        }
                    }
                    updateFormDataStats();
                });
            }
            
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 100);
            
            updateFormDataStats();
        };

        const handleBulkAddFields = () => {
            const textarea = document.createElement('textarea');
            textarea.className = 'w-full h-32 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500';
            textarea.placeholder = '请输入字段，每行一个，格式：\n字段名=字段值\n或\n字段名:字段值';
            
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            modal.innerHTML = `
                <div class="bg-white rounded-lg p-6 w-96">
                    <h3 class="text-lg font-semibold mb-4">批量添加表单字段</h3>
                    <div class="mb-4">
                        ${textarea.outerHTML}
                        <div class="text-sm text-gray-500 mt-2">
                            支持格式：字段名=字段值 或 字段名:字段值
                        </div>
                    </div>
                    <div class="flex space-x-2">
                        <button id="bulk-add-confirm" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">添加</button>
                        <button id="bulk-add-cancel" class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded">取消</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            const textareaElement = modal.querySelector('textarea');
            textareaElement.focus();
            
            modal.querySelector('#bulk-add-confirm').addEventListener('click', () => {
                const text = textareaElement.value.trim();
                if (text) {
                    const lines = text.split('\n').filter(line => line.trim());
                    lines.forEach(line => {
                        const separators = ['=', ':'];
                        let key = '', value = '';
                        
                        for (const sep of separators) {
                            if (line.includes(sep)) {
                                const [k, ...v] = line.split(sep);
                                key = k.trim();
                                value = v.join(sep).trim();
                                break;
                            }
                        }
                        
                        if (key) {
                            addFormFieldRow(key, value);
                        }
                    });
                }
                document.body.removeChild(modal);
            });
            
            modal.querySelector('#bulk-add-cancel').addEventListener('click', () => {
                document.body.removeChild(modal);
            });
            
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    document.body.removeChild(modal);
                }
            });
        };

        const handleFileSelect = () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.onchange = (e) => {
                Array.from(e.target.files).forEach(file => {
                    addFormFieldRow(file.name.replace(/\.[^/.]+$/, ""), '', 'file', file);
                });
            };
            input.click();
        };

        // 更新表单数据统计
        const updateFormDataStats = () => {
            const formDataStats = document.getElementById('form-data-stats');
            const formFieldRows = document.querySelectorAll('.form-field-row');
            
            if (formDataStats) {
                const fieldCount = formFieldRows.length;
                const fileCount = Array.from(formFieldRows).filter(row => {
                    const typeSelect = row.querySelector('[data-role="field-type"]');
                    return typeSelect && typeSelect.value === 'file';
                }).length;
                
                formDataStats.innerHTML = `${fieldCount} 字段 | ${fileCount} 文件`;
            }
        };

        // 全局函数用于字段类型切换
        window.toggleFieldInput = (selectElement) => {
            const container = selectElement.nextElementSibling;
            const type = selectElement.value;
            
            if (type === 'file') {
                const fieldId = `field-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
                container.innerHTML = `
                    <div class="flex items-center space-x-2">
                        <input type="file" class="hidden" id="${fieldId}" data-role="field-file">
                        <button type="button" onclick="document.getElementById('${fieldId}').click()" class="px-3 py-2 bg-gray-100 border border-gray-300 rounded hover:bg-gray-200">
                            选择文件
                        </button>
                    </div>
                `;
                
                // 为新的文件输入添加事件监听器
                const fileInput = container.querySelector('[data-role="field-file"]');
                if (fileInput) {
                    fileInput.addEventListener('change', (e) => {
                        const file = e.target.files[0];
                        if (file) {
                            const button = container.querySelector('button');
                            if (button) {
                                button.textContent = file.name;
                            }
                            const fileDiv = container.querySelector('div');
                            fileDiv.insertAdjacentHTML('beforeend', `<span class="text-sm text-gray-500">(${DevToolsUtils.formatFileSize(file.size)})</span>`);
                        }
                        updateFormDataStats();
                    });
                }
            } else {
                container.innerHTML = `
                    <input type="text" placeholder="字段值" class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" data-role="field-value">
                `;
            }
            
            updateFormDataStats();
        };
        
        // 处理模板选择
        const handleTemplateSelect = () => {
            if (!templateSelect) return;
            
            const templateKey = templateSelect.value;
            if (!templateKey) return;
            
            const templatesResult = APITester.getTemplates();
            if (templatesResult.success && templatesResult.data[templateKey]) {
                const template = templatesResult.data[templateKey];
                loadRequestConfig(template.config);
                DevToolsUtils.showToast(`已加载模板: ${template.name}`, 'success');
            }
            
            templateSelect.value = '';
        };
        
        // 加载请求配置
        const loadRequestConfig = (config) => {
            if (requestUrl) requestUrl.value = config.url || '';
            if (httpMethod) httpMethod.value = config.method || 'GET';
            
            // 清空现有配置
            if (headersContainer) headersContainer.innerHTML = '';
            
            // 加载请求头
            if (config.headers) {
                Object.entries(config.headers).forEach(([key, value]) => {
                    addHeaderRow(key, value);
                });
            }
            
            // 加载请求体
            if (config.body && bodyText) {
                bodyText.value = typeof config.body === 'string' ? config.body : JSON.stringify(config.body, null, 2);
                if (bodyType) {
                    bodyType.value = 'json';
                    handleBodyTypeChange();
                }
            }
        };
        
        // 导入cURL
        const handleImportCurl = () => {
            if (!curlInput) return;
            
            const curlCommand = curlInput.value.trim();
            if (!curlCommand) {
                DevToolsUtils.showToast('请输入cURL命令', 'warning');
                return;
            }
            
            const result = APITester.parseCurl(curlCommand);
            if (result.success) {
                loadRequestConfig(result.data);
                hideModal('curl-modal');
                curlInput.value = '';
                DevToolsUtils.showToast('cURL命令导入成功', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        };
        
        // 导出cURL
        const handleExportCurl = () => {
            const config = getRequestConfig();
            const result = APITester.generateCurl(config);
            
            if (result.success) {
                DevToolsUtils.copyToClipboard(result.data);
                DevToolsUtils.showToast('cURL命令已复制到剪贴板', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        };
        
        // 格式化响应
        const formatResponse = () => {
            if (!currentResponse) return;
            
            const result = APITester.formatResponse(currentResponse.response);
            if (result.success && responseBody) {
                responseBody.textContent = result.data.formatted;
                DevToolsUtils.showToast('响应格式化成功', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        };
        
        // 复制响应
        const copyResponse = async () => {
            if (!currentResponse || !responseBody) return;
            
            const success = await DevToolsUtils.copyToClipboard(responseBody.textContent);
            if (success) {
                DevToolsUtils.showToast('响应内容已复制', 'success');
            }
        };
        
        // 下载响应
        const downloadResponse = () => {
            if (!currentResponse || !responseBody) return;
            
            const blob = new Blob([responseBody.textContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `api-response-${Date.now()}.txt`;
            a.click();
            URL.revokeObjectURL(url);
            
            DevToolsUtils.showToast('响应文件已下载', 'success');
        };
        
        // 保存当前请求
        const saveCurrentRequest = () => {
            const config = getRequestConfig();
            if (!config.url.trim()) {
                DevToolsUtils.showToast('请先配置请求URL', 'warning');
                return;
            }
            
            const mockResponse = {
                status: 0,
                statusText: 'Saved',
                headers: {},
                size: 0,
                duration: 0
            };
            
            APITester.saveToHistory(config, mockResponse);
            loadHistory();
            DevToolsUtils.showToast('请求已保存', 'success');
        };
        
        // 加载历史记录
        const loadHistory = () => {
            if (!historyContainer) return;
            
            const result = APITester.getHistory();
            if (result.success && result.data.length > 0) {
                const historyHtml = result.data.map(item => `
                    <div class="history-item p-3 border rounded-lg hover:bg-gray-50 cursor-pointer" data-config='${JSON.stringify(item.config)}'>
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <span class="px-2 py-1 text-xs font-medium rounded ${getMethodColor(item.config.method)}">
                                    ${item.config.method}
                                </span>
                                <span class="text-sm font-medium text-gray-900 truncate">${item.config.url}</span>
                            </div>
                            <div class="flex items-center gap-2 text-xs text-gray-500">
                                ${item.response.status > 0 ? `<span class="status-${APITester.getStatusInfo(item.response.status).type}">${item.response.status}</span>` : ''}
                                <span>${new Date(item.timestamp).toLocaleString()}</span>
                            </div>
                        </div>
                    </div>
                `).join('');
                
                historyContainer.innerHTML = historyHtml;
                
                // 添加点击事件
                historyContainer.querySelectorAll('.history-item').forEach(item => {
                    item.addEventListener('click', () => {
                        const config = JSON.parse(item.dataset.config);
                        loadRequestConfig(config);
                        DevToolsUtils.showToast('历史请求已加载', 'success');
                    });
                });
            } else {
                historyContainer.innerHTML = `
                    <div class="text-center text-gray-500 py-8">
                        <i data-feather="clock" class="w-12 h-12 mx-auto mb-2 text-gray-300"></i>
                        <p>暂无请求历史</p>
                    </div>
                `;
            }
            
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 100);
        };
        
        // 获取方法颜色
        const getMethodColor = (method) => {
            const colors = {
                'GET': 'bg-green-100 text-green-800',
                'POST': 'bg-blue-100 text-blue-800',
                'PUT': 'bg-orange-100 text-orange-800',
                'PATCH': 'bg-yellow-100 text-yellow-800',
                'DELETE': 'bg-red-100 text-red-800',
                'HEAD': 'bg-purple-100 text-purple-800',
                'OPTIONS': 'bg-gray-100 text-gray-800'
            };
            return colors[method] || 'bg-gray-100 text-gray-800';
        };
        
        // 导出历史
        const exportHistory = () => {
            const result = APITester.getHistory();
            if (result.success && result.data.length > 0) {
                const exportResult = APITester.exportCollection(result.data);
                if (exportResult.success) {
                    const url = URL.createObjectURL(exportResult.data.blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = exportResult.data.filename;
                    a.click();
                    URL.revokeObjectURL(url);
                    
                    DevToolsUtils.showToast('历史记录已导出', 'success');
                } else {
                    DevToolsUtils.showToast(exportResult.error, 'error');
                }
            } else {
                DevToolsUtils.showToast('没有可导出的历史记录', 'warning');
            }
        };
        
        // 清空历史
        const clearHistory = () => {
            if (confirm('确定要清空所有历史记录吗？')) {
                APITester.clearHistory();
                loadHistory();
                DevToolsUtils.showToast('历史记录已清空', 'success');
            }
        };
        
        // 清空所有
        const clearAll = () => {
            if (confirm('确定要清空所有配置吗？')) {
                if (requestUrl) requestUrl.value = '';
                if (httpMethod) httpMethod.value = 'GET';
                if (headersContainer) headersContainer.innerHTML = '';
                if (bodyText) bodyText.value = '';
                if (paramsContainer) paramsContainer.innerHTML = '';
                if (authType) {
                    authType.value = 'none';
                    handleAuthTypeChange();
                }
                if (bodyType) {
                    bodyType.value = 'none';
                    handleBodyTypeChange();
                }
                if (responseSection) responseSection.style.display = 'none';
                
                addHeaderRow();
                DevToolsUtils.showToast('所有配置已清空', 'success');
            }
        };
        
        // 加载环境变量
        const loadEnvironments = () => {
            APITester.getEnvironments();
        };
        
        // 环境管理功能实现
        const setupEnvironmentManagement = () => {
            const envModal = document.getElementById('environment-modal');
            const closeEnvModal = document.getElementById('close-env-modal');
            const addEnvironmentBtn = document.getElementById('add-environment');
            const environmentsList = document.getElementById('environments-list');
            const environmentSelect = document.getElementById('environment-select');
            
            if (closeEnvModal) {
                closeEnvModal.addEventListener('click', () => hideModal('environment-modal'));
            }
            
            if (addEnvironmentBtn) {
                addEnvironmentBtn.addEventListener('click', () => {
                    const name = prompt('请输入环境名称:');
                    if (name) {
                        APITester.setEnvironment(name, {});
                        loadEnvironmentsList();
                        loadEnvironmentSelect();
                        DevToolsUtils.showToast(`环境 "${name}" 已创建`, 'success');
                    }
                });
            }
            
            const loadEnvironmentsList = () => {
                if (!environmentsList) return;
                
                const result = APITester.getEnvironments();
                if (result.success) {
                    const envs = result.data.list;
                    const html = Object.entries(envs).map(([key, env]) => `
                        <div class="border rounded-lg p-4 mb-4">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="font-medium text-gray-800">${env.name}</h4>
                                <div class="flex gap-2">
                                    <button class="edit-env text-blue-600 hover:text-blue-700 text-sm" data-env="${key}">
                                        <i data-feather="edit-2" class="w-4 h-4"></i>
                                    </button>
                                    ${key !== 'default' ? `<button class="delete-env text-red-600 hover:text-red-700 text-sm" data-env="${key}">
                                        <i data-feather="trash-2" class="w-4 h-4"></i>
                                    </button>` : ''}
                                </div>
                            </div>
                            <div class="text-sm text-gray-600">
                                变量数量: ${Object.keys(env.variables || {}).length}
                            </div>
                            <div class="mt-2 text-xs text-gray-500">
                                ${Object.keys(env.variables || {}).slice(0, 3).join(', ')}
                                ${Object.keys(env.variables || {}).length > 3 ? '...' : ''}
                            </div>
                        </div>
                    `).join('');
                    
                    environmentsList.innerHTML = html;
                    
                    // 添加编辑和删除事件
                    environmentsList.querySelectorAll('.edit-env').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const envKey = btn.dataset.env;
                            editEnvironment(envKey);
                        });
                    });
                    
                    environmentsList.querySelectorAll('.delete-env').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const envKey = btn.dataset.env;
                            if (confirm(`确定要删除环境 "${envKey}" 吗？`)) {
                                APITester.deleteEnvironment(envKey);
                                loadEnvironmentsList();
                                loadEnvironmentSelect();
                                DevToolsUtils.showToast(`环境 "${envKey}" 已删除`, 'success');
                            }
                        });
                    });
                    
                    setTimeout(() => {
                        if (typeof feather !== 'undefined') {
                            feather.replace();
                        }
                    }, 10);
                }
            };
            
            const loadEnvironmentSelect = () => {
                if (!environmentSelect) return;
                
                const result = APITester.getEnvironments();
                if (result.success) {
                    const envs = result.data.list;
                    const current = result.data.current;
                    
                    environmentSelect.innerHTML = Object.entries(envs).map(([key, env]) => 
                        `<option value="${key}" ${key === current ? 'selected' : ''}>${env.name}</option>`
                    ).join('');
                }
            };
            
            const editEnvironment = (envKey) => {
                const result = APITester.getEnvironments();
                if (result.success && result.data.list[envKey]) {
                    const env = result.data.list[envKey];
                    const variables = env.variables || {};
                    
                    let variablesText = Object.entries(variables).map(([k, v]) => `${k}=${v}`).join('\n');
                    const newVariablesText = prompt(`编辑环境变量 (格式: key=value，每行一个):\n\n当前变量:`, variablesText);
                    
                    if (newVariablesText !== null) {
                        const newVariables = {};
                        newVariablesText.split('\n').forEach(line => {
                            const [key, ...valueParts] = line.split('=');
                            if (key && key.trim()) {
                                newVariables[key.trim()] = valueParts.join('=').trim();
                            }
                        });
                        
                        APITester.setEnvironment(envKey, newVariables);
                        loadEnvironmentsList();
                        DevToolsUtils.showToast(`环境 "${envKey}" 已更新`, 'success');
                    }
                }
            };
            
            // 初始化环境数据
            loadEnvironmentsList();
            loadEnvironmentSelect();
            
            // 环境切换事件
            if (environmentSelect) {
                environmentSelect.addEventListener('change', () => {
                    const selectedEnv = environmentSelect.value;
                    APITester.switchEnvironment(selectedEnv);
                    DevToolsUtils.showToast(`已切换到环境: ${selectedEnv}`, 'success');
                });
            }
        };
        
        // 代码生成器功能实现
        const setupCodeGenerator = () => {
            const codeModal = document.getElementById('code-generator-modal');
            const closeCodeModal = document.getElementById('close-code-modal');
            const codeLanguage = document.getElementById('code-language');
            const generateCodeBtn = document.getElementById('generate-code');
            const copyCodeBtn = document.getElementById('copy-code');
            const downloadCodeBtn = document.getElementById('download-code');
            const generatedCode = document.getElementById('generated-code');
            const codeStats = document.getElementById('code-stats');
            
            if (closeCodeModal) {
                closeCodeModal.addEventListener('click', () => hideModal('code-generator-modal'));
            }
            
            const updateCodeStats = (code) => {
                if (codeStats && code) {
                    const lines = code.split('\n').length;
                    const chars = code.length;
                    codeStats.textContent = `代码行数: ${lines} | 字符数: ${chars}`;
                }
            };
            
            const generateCode = () => {
                const config = getRequestConfig();
                const language = codeLanguage ? codeLanguage.value : 'curl';
                
                const result = APITester.generateCode(config, language);
                if (result.success && generatedCode) {
                    generatedCode.textContent = result.data;
                    updateCodeStats(result.data);
                    DevToolsUtils.showToast('代码生成成功', 'success');
                } else {
                    generatedCode.textContent = result.error || '代码生成失败';
                    updateCodeStats('');
                    DevToolsUtils.showToast(result.error || '代码生成失败', 'error');
                }
            };
            
            if (generateCodeBtn) {
                generateCodeBtn.addEventListener('click', generateCode);
            }
            
            // 语言切换时自动重新生成
            if (codeLanguage) {
                codeLanguage.addEventListener('change', generateCode);
            }
            
            if (copyCodeBtn && generatedCode) {
                copyCodeBtn.addEventListener('click', () => {
                    if (generatedCode.textContent.trim()) {
                        DevToolsUtils.copyToClipboard(generatedCode.textContent);
                        DevToolsUtils.showToast('代码已复制到剪贴板', 'success');
                    } else {
                        DevToolsUtils.showToast('没有可复制的代码', 'warning');
                    }
                });
            }
            
            if (downloadCodeBtn && generatedCode && codeLanguage) {
                downloadCodeBtn.addEventListener('click', () => {
                    if (!generatedCode.textContent.trim()) {
                        DevToolsUtils.showToast('没有可下载的代码', 'warning');
                        return;
                    }
                    
                    const language = codeLanguage.value;
                    const extensions = {
                        'curl': 'sh',
                        'javascript': 'js',
                        'javascript-axios': 'js',
                        'javascript-jquery': 'js',
                        'python': 'py',
                        'python-urllib': 'py',
                        'nodejs': 'js',
                        'nodejs-axios': 'js',
                        'php': 'php',
                        'php-guzzle': 'php',
                        'java': 'java',
                        'csharp': 'cs',
                        'go': 'go',
                        'ruby': 'rb',
                        'swift': 'swift',
                        'kotlin': 'kt'
                    };
                    
                    const extension = extensions[language] || 'txt';
                    const filename = `api-request.${extension}`;
                    
                    const blob = new Blob([generatedCode.textContent], { type: 'text/plain' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    a.click();
                    URL.revokeObjectURL(url);
                    
                    DevToolsUtils.showToast(`代码已下载为 ${filename}`, 'success');
                });
            }
        };
        
        // 性能分析功能实现
        const setupPerformanceAnalyzer = () => {
            const perfModal = document.getElementById('performance-modal');
            const closePerfModal = document.getElementById('close-perf-modal');
            const performanceReport = document.getElementById('performance-report');
            
            if (closePerfModal) {
                closePerfModal.addEventListener('click', () => hideModal('performance-modal'));
            }
            
            const generatePerformanceReport = () => {
                if (!performanceReport) return;
                
                const history = APITester.getHistory();
                if (history.success && history.data.length > 0) {
                    const responses = history.data.map(item => item.response);
                    const analysis = APITester.analyzePerformance(responses);
                    
                    if (analysis.success) {
                        const data = analysis.data;
                        performanceReport.innerHTML = `
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                                <div class="bg-blue-50 p-4 rounded-lg">
                                    <h4 class="font-semibold text-blue-800 mb-2">请求统计</h4>
                                    <div class="space-y-1 text-sm">
                                        <div>总数: ${data.requests.total}</div>
                                        <div>成功: ${data.requests.successful}</div>
                                        <div>失败: ${data.requests.failed}</div>
                                    </div>
                                </div>
                                <div class="bg-green-50 p-4 rounded-lg">
                                    <h4 class="font-semibold text-green-800 mb-2">响应时间 (ms)</h4>
                                    <div class="space-y-1 text-sm">
                                        <div>平均: ${data.timing.average}</div>
                                        <div>最小: ${data.timing.min}</div>
                                        <div>最大: ${data.timing.max}</div>
                                        <div>中位数: ${data.timing.median}</div>
                                    </div>
                                </div>
                                <div class="bg-purple-50 p-4 rounded-lg">
                                    <h4 class="font-semibold text-purple-800 mb-2">数据大小</h4>
                                    <div class="space-y-1 text-sm">
                                        <div>平均: ${DevToolsUtils.formatFileSize(data.size.average)}</div>
                                        <div>最小: ${DevToolsUtils.formatFileSize(data.size.min)}</div>
                                        <div>最大: ${DevToolsUtils.formatFileSize(data.size.max)}</div>
                                        <div>总计: ${DevToolsUtils.formatFileSize(data.size.total)}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-gray-800 mb-2">状态码分布</h4>
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                                    ${Object.entries(data.statusCodes).map(([code, count]) => 
                                        `<div>${code}: ${count}</div>`
                                    ).join('')}
                                </div>
                            </div>
                        `;
                    } else {
                        performanceReport.innerHTML = `<p class="text-red-600">${analysis.error}</p>`;
                    }
                } else {
                    performanceReport.innerHTML = `<p class="text-gray-600">没有足够的历史数据进行性能分析</p>`;
                }
            };
            
            // 当模态框显示时生成报告
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.target === perfModal && !perfModal.classList.contains('hidden')) {
                        generatePerformanceReport();
                    }
                });
            });
            
            if (perfModal) {
                observer.observe(perfModal, { attributes: true, attributeFilter: ['class'] });
            }
        };
        
        // 批量运行功能实现
        const setupCollectionRunner = () => {
            const runnerModal = document.getElementById('collection-runner-modal');
            const closeRunnerModal = document.getElementById('close-runner-modal');
            const collectionToRun = document.getElementById('collection-to-run');
            const runnerEnvironment = document.getElementById('runner-environment');
            const startRunnerBtn = document.getElementById('start-runner');
            const cancelRunnerBtn = document.getElementById('cancel-runner');
            const runnerResults = document.getElementById('runner-results');
            
            if (closeRunnerModal) {
                closeRunnerModal.addEventListener('click', () => hideModal('collection-runner-modal'));
            }
            
            if (cancelRunnerBtn) {
                cancelRunnerBtn.addEventListener('click', () => hideModal('collection-runner-modal'));
            }
            
            if (startRunnerBtn) {
                startRunnerBtn.addEventListener('click', () => {
                    const selectedCollection = collectionToRun ? collectionToRun.value : '';
                    if (!selectedCollection) {
                        DevToolsUtils.showToast('请选择要运行的集合', 'warning');
                        return;
                    }
                    
                    // 模拟批量运行（这里可以扩展为真实的集合运行）
                    const mockCollection = {
                        name: '测试集合',
                        requests: [
                            {
                                name: '获取用户列表',
                                config: {
                                    url: 'https://jsonplaceholder.typicode.com/users',
                                    method: 'GET',
                                    headers: { 'Accept': 'application/json' }
                                }
                            },
                            {
                                name: '创建新用户',
                                config: {
                                    url: 'https://jsonplaceholder.typicode.com/users',
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({ name: 'Test User', email: 'test@example.com' })
                                }
                            }
                        ]
                    };
                    
                    DevToolsUtils.showToast('开始批量运行...', 'info');
                    
                    APITester.runCollection(mockCollection, runnerEnvironment ? runnerEnvironment.value : null)
                        .then(result => {
                            if (result.success && runnerResults) {
                                runnerResults.classList.remove('hidden');
                                const summary = result.data.summary;
                                runnerResults.innerHTML = `
                                    <h4 class="font-semibold mb-2">运行结果</h4>
                                    <div class="bg-gray-50 p-3 rounded text-sm">
                                        <div>总请求数: ${summary.total}</div>
                                        <div>成功: ${summary.passed}</div>
                                        <div>失败: ${summary.failed}</div>
                                        <div>耗时: ${summary.duration}ms</div>
                                    </div>
                                `;
                                DevToolsUtils.showToast('批量运行完成', 'success');
                            } else {
                                DevToolsUtils.showToast(result.error || '批量运行失败', 'error');
                            }
                        });
                });
            }
            
            // 加载环境选项
            const loadRunnerEnvironments = () => {
                if (!runnerEnvironment) return;
                
                const result = APITester.getEnvironments();
                if (result.success) {
                    const envs = result.data.list;
                    runnerEnvironment.innerHTML = '<option value="">使用当前环境</option>' + 
                        Object.entries(envs).map(([key, env]) => 
                            `<option value="${key}">${env.name}</option>`
                        ).join('');
                }
            };
            
            loadRunnerEnvironments();
            
            // 加载集合选项（模拟数据）
            if (collectionToRun) {
                collectionToRun.innerHTML = `
                    <option value="">选择要运行的集合...</option>
                    <option value="test-collection">测试集合</option>
                    <option value="api-collection">API集合</option>
                `;
            }
        };
        
        // 显示/隐藏模态框
        const showModal = (modalId) => {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.remove('hidden');
            }
        };
        
        const hideModal = (modalId) => {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.add('hidden');
            }
        };
        
        // 初始化应用
        initializeRenderer();
        
        // 初始化所有高级功能
        setupEnvironmentManagement();
        setupCodeGenerator();
        setupPerformanceAnalyzer();
        setupCollectionRunner();
        
        // 必须的图标初始化
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
        
        DevToolsUtils.showToast('API测试工具增强版已加载完成！', 'success');
    }
};